package com.framework.dubbo.producer.file2html;

import cn.hutool.core.util.StrUtil;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.FileURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.List;

/**
 * 基于回调的实现文档预览
 * @author xianggj
 * @Date 2021/6/7 14:12
 **/
public class WordFilePreviewer extends AbstractFilePreviewTools {

    public WordFilePreviewer() {
    }

    @Override
    public String convert2Html(String path) {
        return word2Html(path);
    }

    @Override
    public String convert2Html(InputStream in, String ext) {
        try {
            if (FileType.DOC.getValue().equalsIgnoreCase(ext)){
                return doc2Html(in);
            } else {
                return docx2Html(in);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        return "文件转换错误";
    }

    @Override
    public String convert2Str(InputStream in, String ext) {
        String result = "";
        try {
            if (ext.equals(FileType.DOC.getValue())) {
                HWPFDocument doc = new HWPFDocument(in);
                result = doc.getText().toString();
            } else if (ext.equals(FileType.DOCX.getValue())) {
                XWPFDocument doc07 = new XWPFDocument(in);
                List<XWPFParagraph> paras = doc07.getParagraphs();
                for(XWPFParagraph para: paras) {
                    result += para.getText().toString();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }


    /**
     * 2007版本word转换成html
     * @throws IOException
     */
    public String word2Html(String path) {
        File f = new File(path);
        if (!f.exists()) {
            return String.format("文件[%s]不存在", path);
        } else {
            String ext = StrUtil.subAfter(path, ".", true).toLowerCase();
            try (InputStream in = new FileInputStream(f)) {
                if (FileType.DOCX.getValue().equals(ext)) {
                    return docx2Html(in);
                } else if (FileType.DOC.getValue().equals(ext)) {
                    return doc2Html(in);
                } else {
                    return ext + "文件不支持！";
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return String.format("文件[%s]不存在", path);
            } catch (Exception e) {
                e.printStackTrace();
                return "文件解析失败";
            }
        }
    }

    public String docx2Html(InputStream in) throws IOException {
        XWPFDocument document = new XWPFDocument(in);
        String imagePath = getLocalDir();
        File imageFolderFile = new File(imagePath);
        XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(imageFolderFile));
        options.setExtractor(new FileImageExtractor(imageFolderFile));
        options.setIgnoreStylesIfUnused(false);
        options.setFragment(true);
        options.URIResolver((uri)->{
            File imgFile = new File(imagePath + File.separator +  uri);//获取图片
            String imgName = System.currentTimeMillis() + "_"+imgFile.getName();//设置图片文件名
            InputStream is= null;
            try {
                is = new FileInputStream(imgFile);
                String ext = StrUtil.subAfter(imgName, ".", true);
                return writeToLocal(is, ext);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "";//返回图片url
        });

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        XHTMLConverter.getInstance().convert(document, baos, options);
        String content = baos.toString("UTF-8");
        content = StrUtil.replace(content, "\"", "'");
        try {
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }

    /**
     * /**
     * 2003版本word转换成html
     * @throws IOException
     * @throws TransformerException
     * @throws ParserConfigurationException
     */
    public String doc2Html(InputStream input) throws
            IOException, ParserConfigurationException, TransformerException {
        HWPFDocument wordDocument = new HWPFDocument(input);
        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        //设置图片存放的位置
        wordToHtmlConverter.setPicturesManager(new PicturesManager() {
            @Override
            public String savePicture(byte[] content, PictureType pictureType,
                                      String suggestedName, float widthInches, float heightInches) {
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content);
                String ext = StrUtil.subAfter(suggestedName, ".", true);
                return writeToLocal(byteArrayInputStream, ext);
            }
        });
        //解析word文档
        wordToHtmlConverter.processDocument(wordDocument);
        Document htmlDocument = wordToHtmlConverter.getDocument();

        //也可以使用字符数组流获取解析的内容
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStream outStream = new BufferedOutputStream(baos);

        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(outStream);

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer serializer = factory.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "no");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");

        serializer.transform(domSource, streamResult);

        //也可以使用字符数组流获取解析的内容
        String content = baos.toString("UTF-8");
        content = StrUtil.replace(content, "\"", "'");
        try {
            baos.close();
            outStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }

    public static void main(String[] args) throws FileNotFoundException {
        File sourceFile = new File("C:\\Users\\ZHAOJIAN\\Desktop\\测试文件\\部署注意事项.doc");
        FileInputStream fis = new FileInputStream(sourceFile);
        String s = new WordFilePreviewer().convert2Str(fis, "doc");
        System.out.println(StrUtil.cleanBlank(s));

        System.out.println("========================================================================================");

        File sourceFile2 = new File("C:\\Users\\ZHAOJIAN\\Desktop\\测试文件\\安装git.docx");
        FileInputStream fis2 = new FileInputStream(sourceFile2);
        String dcox = new WordFilePreviewer().convert2Str(fis2, "docx");
        System.out.println(StrUtil.cleanBlank(dcox));
    }
}
